<template>
  <div id="amisPreviewBox"></div>
</template>

<script lang="ts" setup>
import {getToken} from '@/utils/auth';
import cache from '@/plugins/cache'
import errorCode from '@/utils/errorCode'

import {nextTick, onMounted, watch} from "vue";
import {ElMessage, ElMessageBox, ElNotification} from 'element-plus';
import {logoutSystem} from '@/utils/user';
import request from '@/utils/request';

const props = defineProps({
  amisjson: {
    type: Object,
    required: true
  }
})

/**
 * 初始化 AMIS DOM 组件
 *
 * 使用 amisRequire 方法引入 AMIS 库，并通过 amis.embed 方法将 AMIS JSON 配置嵌入到指定的 DOM 元素中。
 */
function amisInitDom() {
  // @ts-ignore
  var amis = amisRequire('amis/embed');
  amis.embed('#amisPreviewBox', props.amisjson, {}, {
    fetcher: (req: any) => {
      let {
        url,
        method,
        data,
        query,
        config,
        headers,
      } = req;
      let tUrl = url && url.split('?')[0]
      console.log(url,
          method,
          data,
          query,
          config);
      if (method == 'get') {
        return request({
          url: tUrl,
          method: method,
          params: query,
          headers: {
            Appid: null,
            ...headers
          }
        })
      } else {
        return request({
          url: tUrl,
          method: method,
          data: data,
          headers: {
            Appid: null,
            ...headers
          }
        })
      }
    },
  });
}

let isRelogin = {show: false}

//认证失败
function authenticationFailedAndReLogin() {
  if (!isRelogin.show) {
    isRelogin.show = true
    ElMessageBox.confirm(
        '登录状态已过期，您可以继续留在该页面，或者重新登录',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
        .then(async () => {
          isRelogin.show = false
          logoutSystem()
        })
        .catch(() => {
          isRelogin.show = false
        })
  }
  return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
}

onMounted(() => {
  amisInitDom();
})

watch(() => props.amisjson, (newVal: any) => {
  nextTick().then(() => {
    amisInitDom();
  });
}, {
  deep: true,
  immediate: true,
})

</script>
<style lang="scss" scoped>
#amisPreviewBox {
  height: 100vh;
  width: 100vw;
  box-sizing: border-box;
}
</style>
